package com.sz.sboot.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sz.sboot.common.PageBean;
import com.sz.sboot.entity.TUser;
import com.sz.sboot.mapper.TUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

@Service
public class TUserServiceImpl implements ITUserService {

    @Autowired
    private TUserMapper tUserMapper;

    @Override
    public PageBean<TUser> getAllUsers(int pageIndex, int pageSize, TUser tUser) {
        PageHelper.startPage(pageIndex,pageSize); //开始分页
        Example example=new Example(TUser.class);
        Example.Criteria criteria = example.createCriteria();
        if (tUser!=null && tUser.getUname()!=null){
            criteria.andLike("uname","%"+tUser.getUname()+"%");
        }
        if (tUser!=null && tUser.getRid()>0){
            criteria.andEqualTo("rid",tUser.getRid());
        }
        List<TUser> list=tUserMapper.selectByExample(example);
        //带模糊查询并分页的数据,如果uname为空,则查询所有
        Page<TUser> plist= (Page<TUser>) list;
        PageBean<TUser> pb=new PageBean<>(
                plist.getTotal(),plist.getResult(),
                plist.getPageSize(),plist.getPages(),plist.getPageNum()
        );
        return pb;
    }

    @Override
    public int deleteUsers(int uid) {
        return tUserMapper.deleteByPrimaryKey(uid);
    }

    @Override
    public TUser getUsersById(int uid) {
        return tUserMapper.selectByPrimaryKey(uid);
    }

    @Override
    public int addUsers(TUser tUser) {
        int n=tUserMapper.insertSelective(tUser);
        System.out.println(tUser.getUid()); //得到主键ID
        return n;
    }

    @Override
    public int updateUsers(TUser tUser) {
        return tUserMapper.updateByPrimaryKeySelective(tUser);
    }

    @Override
    public int deleteByUids(List<Integer> luids) {
        Example example=new Example(TUser.class);
        Example.Criteria criteria = example.createCriteria();
        if (luids.size()!=0){
            criteria.andIn("uid",luids);
        }
        return tUserMapper.deleteByExample(example);
    }
}
